#include "linux_def.h"
#include "core.h"


void process_send(event_t *wev)
{
	int n;
	connection_t	*c;
	
	c = wev->data;


	if (wev->timedout){
		wev->timedout = 0;
		wev->delay = 0;
	}

	if (verbose)
		printf("%s, %d, %s\n", __FILE__, __LINE__, __func__);

	if (wev->ready){
		n = c->send(c, c->buf, strlen(c->buf));
		free(c->buf);
	}
	
	if (verbose)
		printf("%s, %d, %s\n", __FILE__, __LINE__, __func__);

	close_connection(c);
	
	return;
}


void request_handler(event_t *rev)
{
	int	n, size;
	g_time_t	*tp;
	request_time	*r;
	connection_t	*c;
	event_t		*wev;

	c = rev->data;	//get出当前连接
	if (rev->timedout){	//读时间超时
		rev->timer_set = 1;	//close connection and set timer flag  
		close_connection(c);
		return;
	}

	//read ready
	if (rev->ready){
		char buffer[6] = {0};
		n = c->recv(c, buffer, 6);
		printf("recvfrom client %s\n", buffer);
		if (n == EAGAIN){
			handle_read_event(rev, 0);
			return;
		}
		if (n != 6){
			close_connection(c);
			return;
		}

		c->buf = (char *)malloc(atoi(buffer)+1);
		c->buf[atoi(buffer)+1] ='\0';
		size = c->recv(c, c->buf, atoi(buffer));
		if (size != atoi(buffer)){
			close_connection(c);
			return;
		}

		printf("recvfrom client %s\n", c->buf);
	}
	
	if (c->read->timer_set){
		event_del_timer(c->read);
	}

	wev = c->write;
	wev->data = c;
	wev->handler =  process_send;

	if (epoll_add_event(wev, WRITE_EVENT, CLEAR_EVENT) == E_FAIL){
		fprintf(stderr, "handle_write_event failed.\n");
		return;
	}


	return;
}


void init_connection(connection_t *c)
{
	event_t	*rev;
	
	rev = c->read;	//读事件在connection
	rev->data = c;	//保存当前的连接
	rev->handler = request_handler;	//读事件执行函数
	c->write->handler = process_send;	//写事件执行函数
	c->read->handler = request_handler;

	if (verbose)
		printf("c->fd = %d . %s, %d, %s\n", c->fd, __FILE__, __LINE__, __func__);

	event_add_timer(rev, c->listening->post_accept_timeout);
	return;
	//读就绪
	if (rev->ready){
/*	
		if (use_accept_mutex){
			post_event(rev, &posted_events);
			return;
		}
*/	
		request_handler(rev);
		return;
	}

	
	if (handle_read_event(rev, 0) == -1){
		close_connection(c);
		return;
	}

}

